跳至内容
GenAIScript logo A yellow square with genai text

生成式AI脚本编写

提示即编码

使用JavaScript以编程方式为大型语言模型(LLM)组装提示。在单个脚本中协调LLM、工具和数据。

  • 用于处理提示的JavaScript工具箱
  • 抽象化设计使其简单易用且高效
  • 无缝的 Visual Studio Code 集成或灵活的命令行
  • 内置支持GitHub Copilot和GitHub Models、OpenAI、Azure OpenAI、Anthropic等

你好世界

假设你想创建一个生成"hello world"诗歌的LLM脚本。你可以编写以下脚本:

$`Write a 'hello world' poem.`

$ 函数是一个模板标签,用于创建提示。该提示随后会被发送到您配置的LLM,由它生成诗歌。

让我们通过添加文件、数据和结构化输出来使其更有趣。假设您想在提示中包含一个文件,然后将输出保存到文件中。您可以编写以下脚本:

// read files
const file = await workspace.readText("data.txt")
// include the file content in the prompt in a context-friendly way
def("DATA", file)
// the task
$`Analyze DATA and extract data in JSON in data.json.`

def 函数包含文件内容,并根据目标LLM的需要进行优化。GenAIScript脚本还会解析LLM输出,并自动提取data.json文件。

播放

下一步

配置您的LLMs

配置secrets以访问您的LLMs。

编写你的第一个脚本

按照入门指南编写您的第一个脚本。

阅读文档

了解更多关于GenAIScript的信息,请参阅脚本参考

A screenshot of VSCode with a genaiscript opened
播放

最新消息 博客

功能特性

GenAIScript 将核心的LLM提示工具整合到一个统一的脚本环境中。

风格化JavaScript

使用JavaScriptTypeScript构建提示的最小化语法。

$`Summarize ${env.files}. Today is ${new Date()}.`

LLM工具

将JavaScript函数注册为LLM工具 (对于不支持工具的模型提供回退方案)。

defTool("weather", "live weather",
{ city: "Paris" }, // schema
async ({ city }) => // callback
{ ... "sunny" }
)

MCP服务器

每个脚本都是一个模型上下文提供工具

script({
parameters: {
question: "What is the weather in Paris?",
},
})
$`Answer the question ${env.parameters.question}.`

LLM智能体

工具内联提示组合成一个代理

defAgent(
"git",
"Agent that answer git questions for the current repo",
"You are a helpful expert in using git.",
{ tools: ["git"] }
)
script({ tools: "agent" })
$`Do a statistical analysis of the last commits`

复用和分享脚本

脚本就是文件!它们可以被版本控制、共享、分叉……

  • Directorygenaisrc
    • my-script.genai.mjs
    • another-great-script.genai.mjs

数据模式

使用schemas定义、验证和修复数据。

const data = defSchema("MY_DATA",
{ type: "array", items: { ... }, })
$`Extract data from files using ${data} schema.`

从PDF、DOCX等文件中提取文本

操作 PDFs, DOCX, …

// automatically convert to text
def("PDF", env.files, { endsWith: ".pdf" })
// or parse and process
const { pages } = await parsers.PDF(env.files[0])

从CSV、XLSX等文件导入表格

操作来自 CSV, XLSX, ...的表格数据

// automatically convert to text
def("DATA", env.files, {
endsWith: ".csv",
// take top 100 rows
sliceHead: 100,
})
// or parse to JavaScript object array
const rows = await parsers.CSV(env.files[0])
// render as markdown table
defData("ROWS", rows, { sliceHead: 100 })

语音转文字

使用OpenAI或其他工具自动转录音频或视频。

const transcript = await transcript("path/to/audio.mp3")
const { srt, vtt, segments } = transcript

图片

在提示中包含图片,我们会为您进行裁剪/调整大小处理。

defImages(images, { autoCrop: true, details: "low" })
播放

视频

使用时间戳甚至转录文本从视频中提取帧。

const frames = await ffmpeg.extractFrames("...", { count: 10 })
defImages(frames, { details: "low" })

生成文件

从LLM输出中提取文件和差异。 在重构UI中预览更改。

$`Save the result in poem.txt.`
FILE ./poem.txt
```txt
The quick brown fox jumps over the lazy dog.
```
  • poem.txt 由genaiscript提取

文件搜索

Grep或模糊搜索文件

const { files } = await workspace.grep(/[a-z][a-z0-9]+/, { globs: "*.md" })

网页搜索

Web search 使用 Bing 或 Tavily。

const pages = await retrieval.webSearch("what are the latest news about AI?")

浏览器自动化

使用Playwright浏览和抓取网页。

const page = await host.browse("https://...")
const table = await page.locator("table[...]").innerHTML()
def("TABLE", await HTML.convertToMarkdown(table))

内置RAG

Vector search 使用本地数据库或Azure AI Search

const index = await retrieval.index("animals", { type: "azure_ai_search" })
await index.insertOrUpdate(env.files)
const docs = await index.search("cat dog")

安全第一!

GenAIScript 提供内置的负责任AI系统提示和Azure内容安全支持,用于验证内容安全

script({ ...,
systemSafety: "default",
contentSafety: "azure" // use azure content safety
})
const safety = await host.contentSafety()
const res = await safety.detectPromptInjection(env.vars.input)

代码解释器

让LLM在沙盒执行环境中运行代码。

script({ tools: ["python_code_interpreter"] })

容器

在Docker 容器中运行代码。

const c = await host.container({
image: "python:alpine",
})
const res = await c.exec("python --version")

LLM组合

Run LLMs 来构建您的LLM提示词。

// summarize each files individually
for (const file of env.files) {
const { text } = await runPrompt((_) => {
_.def("FILE", file)
_.$`Summarize the FILE.`
})
// use result in main prompt
def("SUMMARY", text)
}
// use summary
$`Summarize all the summaries.`

生成图片

生成图片 使用OpenAI DALL-E或其他工具。

const { image, revisedPrompt } = await generateImage(
`a cute cat. only one. photographic, high details. 4k resolution.`
)

分类

对文本、图像或混合内容进行分类。

const joke = await classify(
"Why did the chicken cross the roard? To fry in the sun.",
{
yes: "funny",
no: "not funny",
}
)

Prompty

使用GenAIScript运行或转换Prompty文件。

poem.prompty
---
name: poem
---
system:
Write a short poem about
user:
{{something}}.
importTemplate("poem.prompty", { something: "code " })

可插拔式密钥扫描

使用秘密扫描功能扫描聊天记录中的敏感信息。

genaiscript.config.json
{
"secretPatterns": {
...,
"OpenAI API Key": "sk-[A-Za-z0-9]{32,48}"
}
}

通过CLI实现自动化

使用CLI实现自动化,将报告集成到您的CI/CD流水线中。

npx genaiscript run tlaplus-linter "*.tla"

拉取请求审查

通过评论、代码审查或描述更新将genaiscript集成到您的拉取请求检查中。支持GitHub Actions和Azure DevOps流水线。

npx genaiscript ... --pull-request-reviews

测试与评估

使用测试和评估构建可靠的提示词 由promptfoo提供支持。

script({ ..., tests: {
files: "penguins.csv",
rubric: "is a data analysis report",
facts: "The data refers about penguin population in Antartica.",
}})
Visual Studio Test Explorer opened with a few genaiscript tests.

案例研究

使用GenAIScript的真实案例。

示例

功能完备的脚本,开箱即用。

使用指南

一本充满食谱的烹饪书,助你成为脚本编写高手。

代理

内置代理

LLM友好文档

如果您是LLM爬虫程序,请获取https://microsoft.github.io/genaiscript/llms.txt以查看文档地图, 或在任何文档URL后添加.md后缀以获取原始markdown内容。

例如,https://microsoft.github.io/genaiscript/guides/prompt-as-code.md(注意.md扩展名)